var $;
layui.config({
    base: "js/"
}).use(['form', 'layer', 'jquery', 'laydate', 'upload'], function () {
    var form = layui.form,
        laydate = layui.laydate,
        layer = parent.layer === undefined ? layui.layer : parent.layer,
        laypage = layui.laypage;
    $ = layui.jquery;

    var layerIndex = layer.load(2, {time: 5 * 1000});

    laydate.render({
        elem: '#userBirthday' //指定元素
        , calendar: true
        , format: 'yyyy-M-d'
        , max: minDate()

    });

    function minDate() {
        var now = new Date();
        return now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate();
    }

    /**
     * 查询角色 并回显
     */
    $.ajax({
        type: "GET",
        url: "/tiRole/queryRoleInfo",
        datatype: "json",
        success: function (data) {
            //console.log(data)
            if (data.code == 200) {
                $.each(data.data, function (index, item) {
                    $('#role').append(new Option(item.roleDescription, item.roleId));
                });
                layui.form.render("select");
            }
        }, error: function () {
            $.message({
                message: 'boom..',
                type: 'error',
                showClose: true
            });
        }
    });

    /**
     * 查询用户信息回显
     */
    $.ajax({
        type: "get",
        url: "/tiUsers/getShiroUserInfo",
        datatype: "json",
        success: function (data) {
            //    console.log(data)
            if (data.code == 200) {

                $('.userId').val(data.data.userId);
                $('.userBirthday').val(data.data.userBirthday);
                $('.userName').val(data.data.userName);

                $('.userNickname').val(data.data.userNickname);
                $('.userEmail').val(data.data.userEmail);
                $('.userTelephoneNumber').val(data.data.userTelephoneNumber);
                $('#userFace').attr('src', data.data.userProfilePhoto);
                $("input[type=radio][name='userSex'][value='" + data.data.userSex + "']").attr("checked", 'checked');
                $('.user_pic img').attr('src', data.data.userProfilePhoto);
                /**
                 * 查询用户角色信息 并回显
                 */
                $.ajax({
                    type: "POST",
                    url: "/tiRole/queryUserRoleInfo",
                    datatype: "json",
                    data: {
                        userId: data.data.userId
                    },
                    success: function (data) {
                        //  console.log(data)
                        if (data.code == 200) {
                            $("#role").each(function () {
                                $(this).children("option").each(function () {
                                    if (this.value == data.data.roleId) {
                                        $(this).attr("selected", "selected");
                                        form.render("select");
                                    }
                                    if (data.data.roleId != 1) {
                                        $(this).attr("disabled", 'disabled')
                                    }
                                });
                            })

                        }
                    }, complete: function (XHR, TS) {
                        layer.close(layerIndex);
                    }
                });

                form.render();

            }
        }
    });


    /**
     * 提交个人资料
     */
    form.on("submit(editUserInfo)", function (data) {
        if ($('.userName').val() == '') {
            $.message({
                message: '登录名不能空',
                type: 'warning',
                showClose: true
            });
            return false;
        }

        if ($('.userNickname').val() == '') {
            $.message({
                message: '昵称不能空',
                type: 'warning',
                showClose: true
            });
            return false;
        }

        if ($('.userEmail').val() == '') {
            $.message({
                message: '邮箱不能空',
                type: 'warning',
                showClose: true
            });
            return false;
        }
        var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
        if (!reg.test($('.userEmail').val())) {

            $.message({
                message: '邮箱格式不正确',
                type: 'warning',
                showClose: true
            });
            return false;


        }


        if ($('.userTelephoneNumber').val() == '') {
            $.message({
                message: '手机号码不能空',
                type: 'warning',
                showClose: true
            });
            return false;
        } else {
            var pattern = /^1[34578]\d{9}$/;
            if (!pattern.test($('.userTelephoneNumber').val())) {

                $.message({
                    message: '号码格式不正确',
                    type: 'warning',
                    showClose: true
                });
                return false;
            }

        }

        if ($('.userBirthday').val() == '') {
            $.message({
                message: '生日日期不能空',
                type: 'warning',
                showClose: true
            });
            return false;
        }

        var layerIndex = layer.load(2, {time: 5 * 1000});
        $.ajax({
            type: "PUT",
            url: "/tiUsers/editThisLoginUser",
            datatype: "json",
            data: data.field,
            success: function (data) {
                // console.log(data)
                if (data.code == 101) {
                    $.message({
                        message: data.msg,
                        type: 'warning',
                        showClose: true
                    });
                } else if (data.code == 100) {
                    $.message({
                        message: data.msg,
                        type: 'warning',
                        showClose: true
                    });
                } else {
                    $.message({
                        message: data.msg,
                        type: 'warning',
                        showClose: true
                    });
                }

                if (data.code == 1) {
                    $.message({
                        message: data.msg,
                        type: 'success',
                        showClose: true
                    });
                }

            }, error: function () {
                $.message({
                    message: 'boom..',
                    type: 'error',
                    showClose: true
                });
            }
        });

        layer.close(layerIndex);

        return false;
    })


    /**
     * 修改密码
     */
    form.on("submit(changePwd)", function (data) {

        if ($('.formerPwd').val() == '') {
            $.message({
                message: '请输入旧密码..',
                type: 'warning',
                showClose: true
            });
            return false;
        }

        if ($('.oldPwd').val() == '') {
            $.message({
                message: '请输入新密码..',
                type: 'warning',
                showClose: true
            });
            return false;
        }

        if ($('.newPwd').val() == '') {
            $.message({
                message: '请再次输入新密码..',
                type: 'warning',
                showClose: true
            });
            return false;
        }


        if (($('.oldPwd').val() !== ($('.newPwd').val()))) {
            $.message({
                message: '密码不一致..',
                type: 'warning',
                showClose: true
            });
            return false;
        }


        $.ajax({
            type: "post",
            url: "/tiUsers/editUserPwd",
            datatype: "json",
            data: data.field,
            success: function (data) {
                //  console.log(data)
                if (data.code == 1) {
                    $.message({
                        message: data.msg,
                        type: 'success',
                        showClose: true
                    });
                    setTimeout(function () {
                        //  layer.closeAll("iframe");
                        window.open("/logout", '_top')
                    }, 1000);
                } else {
                    $.message({
                        message: data.msg,
                        type: 'warning',
                        showClose: true
                    });
                }

            }, error: function () {
                $.message({
                    message: 'boom..',
                    type: 'error',
                    showClose: true
                });
            }
        });

        return false;
    })


    //做个下简易的验证  大小 格式
    $('#avatarInput').on('change', function (e) {
        var filemaxsize = 1024 * 5;//5M
        var target = $(e.target);
        var Size = target[0].files[0].size / 1024;
        if (Size > filemaxsize) {
            $.message({
                message: '图片过大，请重新选择！',
                type: 'warning',
                showClose: true
            });

            $(".avatar-wrapper").childre().remove;
            return false;
        }
        if (!this.files[0].type.match(/image.*/)) {
            $.message({
                message: '请选择正确的图片!',
                type: 'warning',
                showClose: true
            });

        } else {
            var filename = document.querySelector("#avatar-name");
            var texts = document.querySelector("#avatarInput").value;
            var teststr = texts; //你这里的路径写错了
            testend = teststr.match(/[^\\]+\.[^\(]+/i); //直接完整文件名的
            filename.innerHTML = testend;
        }

    });

    $(".avatar-save").on("click", function () {
        var img_lg = document.getElementById('imageHead');
        // 截图小的显示框内的内容
        html2canvas(img_lg, {
            allowTaint: true,
            taintTest: false,
            onrendered: function (canvas) {
                canvas.id = "mycanvas";
                //生成base64图片数据
                var dataUrl = canvas.toDataURL("image/jpeg");
                var newImg = document.createElement("img");
                newImg.src = dataUrl;
                imagesAjax(dataUrl)
            }
        });
    })

    function imagesAjax(src) {
        var data = {};
        data.img = src;
        data.jid = $('#jid').val();

        $.ajax({
            url: "/tiUsers/editUserImage",
            data: data,
            type: "PUT",
            dataType: 'json',
            success: function (re) {
                //console.log(re)
                if (re.code == 200) {
                    $.message({
                        message: '操作成功',
                        type: 'success',
                        showClose: true
                    });
                    $('.user_pic img').attr('src', src);
                }
            }
        });
    }


})
